package drds.server.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

import drds.server.net.packet.FieldPacket;
import drds.server.net.packet.RowDataPacket;

public class ResultSetUtil {

	public static int toFlag(ResultSetMetaData metaData, int column) throws SQLException {

		int flags = 0;
		if (metaData.isNullable(column) == 1) {
			flags |= 1;
		}

		if (metaData.isSigned(column)) {
			flags |= 16;
		}

		if (metaData.isAutoIncrement(column)) {
			flags |= 128;
		}

		return flags;
	}

	public static void resultSetToFieldPacket(String charset, List<FieldPacket> fieldPacketList, ResultSet resultSet) throws SQLException {
		ResultSetMetaData metaData = resultSet.getMetaData();
		int colunmCount = metaData.getColumnCount();
		if (colunmCount > 0) {
			for (int i = 0; i < colunmCount; i++) {
				int j = i + 1;
				FieldPacket fieldPacket = new FieldPacket();
				fieldPacket.name = StringUtil.getBytes(metaData.getColumnLabel(j));
				fieldPacket.flags = toFlag(metaData, j);
				fieldPacket.length = metaData.getColumnDisplaySize(j);
				fieldPacket.decimals = (byte) metaData.getScale(j);
				int javaType = MysqlDefs.javaTypeDetect(metaData.getColumnType(j), fieldPacket.decimals);
				fieldPacket.type = (byte) (MysqlDefs.javaTypeMysql(javaType) & 0xff);
				fieldPacketList.add(fieldPacket);
			}
		}

	}

	public static RowDataPacket parseRowData(byte[] row, List<byte[]> fieldValues) {
		RowDataPacket rowDataPkg = new RowDataPacket(fieldValues.size());
		rowDataPkg.read(row);
		return rowDataPkg;
	}

	public static String getColumnValAsString(byte[] row, List<byte[]> fieldValues, int columnIndex) {
		RowDataPacket rowDataPkg = new RowDataPacket(fieldValues.size());
		rowDataPkg.read(row);
		byte[] columnData = rowDataPkg.fieldBytesList.get(columnIndex);
		return new String(columnData);
	}

}
